package allrobots.controller;

import allrobots.DispensingMachineThread.DMFinishToSystem;
import allrobots.DispensingMachineThread.DispensingMachineThread;
import allrobots.Robot.RobotMessage;
import allrobots.Robot.RobotMessageMap;
import allrobots.RobotThread.RobotThread;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import t10086.Data.Map.TextCoordinate;
import t10086.Data.Robot.RobotStatus;
import t10086.Model.Http.Response;

import javax.swing.text.Position;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/systemapi")
@CrossOrigin // 允许所有域的跨域请求
public class RequestRobot {
    @PostMapping("/getrobotlist")
    @ResponseBody
    //收到前端信息后，将两个队列进行比较，启动机器人
    //orders负责保存订单
    //toRobotOrders负责交付订单，看交付和保存大小是否一样
//        System.out.println(orders_num.size());
        // 返回一个Map，Spring会自动转换为JSON

    public Response getrobotlist(@RequestBody Map<String, Object> robotList) throws IOException {
        List<Map<String, Object>> list = (List<Map<String, Object>>) robotList.get("robotList");

        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> robotData = list.get(i);

            // 获取 serialNumber
            String serialNumber = (String) robotData.get("serialNumber");
//            System.out.println("订单号: " + serialNumber);

            // 获取 position 并封装成 Position 类
            Map<String, Object> positionData = (Map<String, Object>) robotData.get("position");
            TextCoordinate position = new TextCoordinate();
            position.setX((Integer) positionData.get("x"));
            position.setY((Integer) positionData.get("y"));
            System.out.println("位置: " + position);
            RobotMessage robot=new RobotMessage(serialNumber,
                    0,position,
                    position,
                    position,
                    RobotStatus.FREE,
                    new InetSocketAddress(0),
                    0,
                    0,
                    position);
            int robotId=Integer.parseInt(serialNumber);
            RobotMessageMap.robotMap.put(robotId,robot);
//            DispensingMachineThread.orders.add("12345");
            new Thread(new RobotThread(robotId)).start();
        }
        new Thread(new DispensingMachineThread()).start();
        return new Response();
    }
}
